package com.neuronbit.businessflow.flow.source;

import com.neuronbit.businessflow.flow.parser.AutoTaskNode;
import com.neuronbit.businessflow.flow.parser.Output;
import com.neuronbit.businessflow.flow.source.util.FieldBuilder;
import com.neuronbit.businessflow.flow.source.util.SourceContext;
import com.neuronbit.businessflow.intellij.model.Node;
import com.neuronbit.businessflow.intellij.model.Type;
import com.neuronbit.businessflow.runtime.StepType;
import com.neuronbit.javaparser.ast.stmt.BlockStmt;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import static java.lang.String.format;

/**
 * The type Auto task node source generator.
 */
@Getter
@Setter
public class AutoTaskStepJavaSource extends UserTaskStepJavaSource {
    /**
     * Instantiates a new Auto task node source generator.
     *
     * @param node          the node
     * @param sourceContext the source context
     */
    public AutoTaskStepJavaSource(Node node, SourceContext sourceContext) {
        super(node, sourceContext);
    }

    @Override
    protected StepType getStepType() {
        return StepType.AUTO_TASK;
    }

    @Override
    protected void writeStepCallStmt(BlockStmt stepCallStmt) {
        AutoTaskNode autoTaskNode = (AutoTaskNode) getNode();
        Output output = autoTaskNode.getOutput();
        String re = "";
        String setStmt = null;
        if (output != null) {
            addImport(output.getType());
            re = output.getType().describe() + " " + output.getName() + "=";
            FieldBuilder fieldBuilder = FieldBuilder.builder(output.getName(), output.getType())
                    .withSetter()
                    .withGetter()
                    .prefix(getNode().getName());
            getContextSource().addField(fieldBuilder);
            setStmt = format("context.set%s(%s);", getNode().getCapitalizeName() + output.getCapitalizeName(), output.getName());
        }
        //call the actual business processing logic
        Type type = autoTaskNode.getType();
        String method = autoTaskNode.getMethodName();
        if (StringUtils.isNoneBlank(re, method) && null != type) {
            addImport(type);
            stepCallStmt.addStatement(format("%s flow.getStepBeanProvider().getBean(%s.class).%s(%s);",
                    re, type.getName(), method, String.join(",", prepareStepParams(stepCallStmt))));
        }
        if (null != setStmt) {
            stepCallStmt.addStatement(setStmt);
        }
    }
}
